import axios from "axios";
import store from "@/store";
import { getToken } from "./auth";
import { Toast } from "vant";
import router from "@/router";

axios.defaults.timeout = 10000;

// request interceptor
axios.interceptors.request.use(
  (config) => {
    if (store.state.token) {
      config.headers["X-Access-Token"] = getToken();
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// response interceptor
axios.interceptors.response.use(
  (response) => {
    const searchParams = new URLSearchParams(location.search.slice(1));
    const token = searchParams.get("token");
    if (response.status === 200) {
      if (response.data.code === 401) {
        localStorage.clear();
        if (!token) {
          Toast("身份信息失效，请重新登录");
        }
        store.dispatch("loginTop", { token });
        setTimeout(() => {
          if (token) {
            return;
          }
          router.push("/login");
        }, 1000);
      } else if (response.data.code === 404) {
        //404
        setTimeout(() => {
          router.push("404");
        }, 1000);
      } else {
        // Toast(response.data.message || 'Error');
        return Promise.resolve(response);
      }
    } else {
      Toast(response.data?.message);
      return Promise.reject(response.data);
    }
    /*if (response.data?.code && response.data?.code !== 200) {
            if (response.data.code === 401) {

                Toast('身份信息失效，请重新登录');
                // store.dispatch('resetToken').then(() => {
                //   location.reload()
                // })
                localStorage.clear()
                setTimeout(() => {
                    router.push('login')
                }, 1000)
            } else {
                Toast(response.data.message || 'Error');
            }
            return Promise.reject(new Error(response.data.message || 'Error'))
        } else {
            return response
        }*/
  },
  (error) => {
    console.log("err" + error); // for debug
    Toast(error.message ? error.message : "请求超时");
    return Promise.reject(error);
  }
);

export function get(url, params, header, forResponse) {
  return new Promise((resolve, reject) => {
    axios
      .get(
        process.env.VUE_APP_BASE_API + url,
        Object.assign(
          {
            params: params,
          },
          header || {}
        )
      )
      .then((res) => {
        if (forResponse) resolve(res);
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

export function post(url, params, header, forResponse) {
  return new Promise((resolve, reject) => {
    axios
      .post(
        process.env.VUE_APP_BASE_API + url,
        Object.assign(params || {}, header || {})
      )
      .then((res) => {
        if (forResponse) resolve(res);
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
